package com.ktjy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjy.dto.BusinessDTO;
import com.ktjy.dto.LoginUser;
import com.ktjy.mapper.*;
import com.ktjy.pojo.*;
import com.ktjy.service.ITbBusinessService;
import com.ktjy.utils.Constants;
import com.ktjy.utils.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 商机 服务实现类
 * </p>
 *
 * @author jjx
 * @since 2025-08-19
 */
@Service
public class TbBusinessServiceImpl extends ServiceImpl<TbBusinessMapper, TbBusiness> implements ITbBusinessService {
    @Autowired
    TbBusinessMapper businessMapper;
    @Autowired
    TbBusinessTrackRecordMapper businessTrackRecordMapper;
    @Autowired
    TbRulePoolMapper rulePoolMapper;
    @Autowired
    TbAssignRecordMapper assignRecordMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    TbClueMapper clueMapper;

    @Override
    public IPage<TbBusiness> findPage(BusinessDTO businessDTO, Integer pageNo, Integer pageSize) {
        //构造分页条件
        Page page=new Page(pageNo,pageSize);
        return businessMapper.getPage(page,businessDTO);
    }
    @Override
    @Transactional
    public void saveBusiness(TbBusiness tbBusiness) {
        LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        //1. 保存线索信息
        //1.1 查询线索池规则
        QueryWrapper qw=new QueryWrapper();
        qw.eq("type",Constants.RULE_TYPE_BUSINESS);
        TbRulePool rulePool = rulePoolMapper.selectOne(qw);
        //指定线索的失效时间
        LocalDateTime endTime= DateUtil.getDate(rulePool.getLimitTime(),rulePool.getLimitTimeType(),
                LocalDateTime.now());
        tbBusiness.setEndTime(endTime);
        this.save(tbBusiness);
        //2. 保存线索分配信息
        TbAssignRecord assignRecord = new TbAssignRecord();
        assignRecord.setAssignId(tbBusiness.getId());
        assignRecord.setUserId(loginUser.getUserId());
        assignRecord.setUserName(loginUser.getUsername());
        assignRecord.setDeptId(loginUser.getDeptId());
        assignRecord.setType(Constants.RULE_TYPE_BUSINESS);
        assignRecordMapper.insert(assignRecord);
    }
    @Override
    @Transactional
    public void assignBusiness(Long businessId, Long userId) {
        //1. 查询线索池规则
        QueryWrapper rulePoolQw=new QueryWrapper();
        rulePoolQw.eq("type", Constants.RULE_TYPE_BUSINESS);
        TbRulePool rulePool = rulePoolMapper.selectOne(rulePoolQw);
        // 2. 统计当前分配人手头拥有的线索数(线索正在跟进还未结束的线索)
        int count = assignRecordMapper.countAssignBusinessByUserId(userId);
        if (count >= rulePool.getMaxNunmber()) {
            throw new RuntimeException("分配失败！系统规则: 商机最大保有量(" + rulePool.getMaxNunmber() + ")，剩余可以分配" + (rulePool.getMaxNunmber() - count) + "条线索");
        }
        // 3. 线索重新分配(修改线索的状态为已分配，待跟进，失效时间为线索规则池时间)
        UpdateWrapper uw=new UpdateWrapper();
        uw.eq("id",businessId);
        uw.set("status",Constants.RULE_TYPE_BUSINESS);
        LocalDateTime endTime= DateUtil.getDate(rulePool.getLimitTime(),rulePool.getLimitTimeType(),
                LocalDateTime.now());
        uw.set("end_time",endTime);
        uw.set("next_time",null);
        this.update(uw);
        //4. 新增线索分配记录
        // 4.1 保留上一条分配记录(修改上一条分配记录为非最新分配记录)
        UpdateWrapper assignRecordUw=new UpdateWrapper();
        assignRecordUw.eq("assign_id",businessId);
        assignRecordUw.eq("type",Constants.RULE_TYPE_BUSINESS);
        assignRecordUw.set("latest","0");
        assignRecordMapper.update(assignRecordUw);
        // 4.2. 新建分配记录
        TbAssignRecord assignRecord = new TbAssignRecord();
        assignRecord.setAssignId(businessId);
        assignRecord.setUserId(userId);
        SysUser sysUser = sysUserMapper.selectById(userId);
        assignRecord.setUserName(sysUser.getUserName());
        assignRecord.setDeptId(sysUser.getDeptId());
        assignRecord.setType(Constants.RULE_TYPE_BUSINESS);
        assignRecordMapper.insert(assignRecord);
    }
    @Override
    @Transactional
    public void backBusiness(Long businessId, String reason) {
        //1.更新商机状态
        UpdateWrapper uw=new UpdateWrapper();
        uw.eq("id",businessId);
        uw.set("status",Constants.FALSE);
        uw.set("next_time",null);
        this.update(uw);
        // 2.保存线索跟进记录
        TbBusinessTrackRecord trackRecord = new TbBusinessTrackRecord();
        trackRecord.setBusinessId(businessId);
        trackRecord.setRecord(reason);
        businessTrackRecordMapper.insert(trackRecord);
    }
    // 重复捞取时间限制
    @Override
    public void gainBusiness(Long id){
        LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        //1. 查询线索池规则
        QueryWrapper qw=new QueryWrapper();
        qw.eq("type",Constants.RULE_TYPE_BUSINESS);
        TbRulePool rulePool = rulePoolMapper.selectOne(qw);
        // 2. 统计当前分配人手头拥有的线索数(线索正在跟进还未结束的线索)
        int count = assignRecordMapper.countAssignBusinessByUserId(id);
        if (count >= rulePool.getMaxNunmber()) {
            throw new RuntimeException("分配失败！系统规则: 商机最大保有量(" + rulePool.getMaxNunmber() + ")，剩余可以分配" + (rulePool.getMaxNunmber() - count) + "条商机");
        }
        // 3.最近捞取记录
        qw=new QueryWrapper();
        qw.eq("assign_id",id);
        qw.eq("type",Constants.RULE_TYPE_BUSINESS);
        qw.eq("latest","1");
        TbAssignRecord assignRecord = assignRecordMapper.selectOne(qw);
        //如果该条线索最近分配人是当前分配人
        if (assignRecord != null && assignRecord.getUserId().equals(loginUser.getUserId())) {
            //计算可以重复捞取的时间过了没
            LocalDateTime repeatGetTime = DateUtil.getDate(rulePool.getRepeatGetTime(),
                    rulePool.getRepeatType(),assignRecord.getCreateTime());
            // 捞取限制时间内，不让捞取
            if (LocalDateTime.now().isBefore(repeatGetTime)) {
                throw new RuntimeException("捞取失败！需要在 " + repeatGetTime + " 后捞取");
            }
        }
        //4. 捞取成功重新分配
        UpdateWrapper uw=new UpdateWrapper();
        uw.eq("id",id);
        uw.set("status",Constants.UNFOLLOWED);
        LocalDateTime endTime= DateUtil.getDate(rulePool.getLimitTime(),rulePool.getLimitTimeType(),
                LocalDateTime.now());
        uw.set("end_time",endTime);
        uw.set("next_time",null);
        this.update(uw);
        //4. 新增线索分配记录
        // 4.1 保留上一条分配记录(修改上一条分配记录为非最新分配记录)
        uw=new UpdateWrapper();
        uw.eq("assign_id",id);
        uw.eq("type",Constants.RULE_TYPE_BUSINESS);
        uw.set("latest","0");
        assignRecordMapper.update(uw);
        // 4.2. 新建分配记录
        assignRecord = new TbAssignRecord();
        assignRecord.setAssignId(id);
        assignRecord.setUserId(loginUser.getUserId());
        SysUser sysUser = sysUserMapper.selectById(loginUser.getUserId());
        assignRecord.setUserName(sysUser.getUserName());
        assignRecord.setDeptId(sysUser.getDeptId());
        assignRecord.setType(Constants.RULE_TYPE_BUSINESS);
        assignRecordMapper.insert(assignRecord);
    }


    @Override
    public void changeBusiness(Long clueId) {
        //1.修改线索状态为 转商机
        UpdateWrapper uw=new UpdateWrapper();
        uw.eq("id",clueId);
        uw.set("status",Constants.TOBUSINESS);
        uw.set("next_time",null);
        clueMapper.update(uw);

        //2.新增商机记录
        //查询出线索对应的数据
        TbClue clue = clueMapper.selectById(clueId);
        //构建商机对象
        TbBusiness business = new TbBusiness();
        //属性复制
        BeanUtils.copyProperties(clue,business);
        business.setCreateBy(null);
        business.setCreateTime(null);
        business.setUpdateBy(null);
        business.setUpdateTime(null);
        business.setStatus(Constants.UNFOLLOWED);
        business.setClueId(clueId);
        business.setNextTime(null);
        //1. 查询线索池规则
        QueryWrapper qw=new QueryWrapper();
        qw.eq("type",Constants.RULE_TYPE_BUSINESS);
        TbRulePool rulePool = rulePoolMapper.selectOne(qw);
        LocalDateTime endTime= DateUtil.getDate(rulePool.getLimitTime(),rulePool.getLimitTimeType(),
                LocalDateTime.now());
        business.setEndTime(endTime);
        //添加商机数据
        this.save(business);

        //3.新增商机分配记录
        TbAssignRecord assignRecord =new TbAssignRecord();
        assignRecord.setAssignId(business.getId());
        //直接写死分给lisi
        assignRecord.setUserId(4l);
        assignRecord.setUserName("lisi");
        assignRecord.setDeptId(216l);
        assignRecord.setType(Constants.RULE_TYPE_BUSINESS);
        assignRecordMapper.insert(assignRecord);
    }
}
